package com.wasion.gydpe.common.aop;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Service;

import com.wasion.gydpe.dao.LogInLogDao;
import com.wasion.gydpe.exception.DataAccessException;
import com.wasion.gydpe.model.LogInLog;

/**
 * 
 * @ClassName: LogInLogAspect
 * @Description: 登录日志切面（配置为注解的方式，方便拔插）
 * @author 高意
 * @date Oct 11, 2012 11:11:45 AM
 * 
 */
@Aspect
@Service
public class LogInLogAspect {

	@Resource
	private LogInLogDao logInLogDao;

	/**
	 * 
	 * @Title: doAfterReturning
	 * @Description: 在某个连接点正常完成后执行的通知（登录成功）
	 * @param
	 * @return
	 * @throws
	 */

	@AfterReturning("execution(* org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(..))")
	public void doAfterReturning(JoinPoint joinPoint) {

		LogInLog log = encapsulateLogInLog(joinPoint, 1);

		try {
			logInLogDao.add(log);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: doAfterThrowing
	 * @Description: 在某个连接点抛出异常退出时执行的通知(登录失败)
	 * @param
	 * @return
	 * @throws
	 */
	@AfterThrowing(pointcut = "execution(* org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(..))")
	public void doAfterThrowing(JoinPoint joinPoint) {

		LogInLog log = encapsulateLogInLog(joinPoint, 0);

		try {
			logInLogDao.add(log);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: encapsulateLogInLog
	 * @Description: 封装登录日志信息
	 * @param
	 * @return
	 * @throws
	 */
	protected LogInLog encapsulateLogInLog(JoinPoint joinPoint,
			int loginStatusFlag) {

		LogInLog log = new LogInLog();
		Object[] args = joinPoint.getArgs();
		UsernamePasswordAuthenticationToken upat = (UsernamePasswordAuthenticationToken) args[0];
		WebAuthenticationDetails wads = (WebAuthenticationDetails) upat
				.getDetails();

		String username = upat.getName();
		log.setUsername(username);
		log.setIpAddr(wads.getRemoteAddress());
		log.setIsLogInSucc(loginStatusFlag); // 登录状态标识
		log.setLogInTime(new Timestamp(System.currentTimeMillis()).toString());

		return log;
	}
}
